package com.yang.community.controller;


import com.yang.community.dto.AccessTokenDTO;
import com.yang.community.dto.GiteeUser;
import com.yang.community.model.User;
import com.yang.community.provider.GiteeProvider;
import com.yang.community.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@Controller
@Slf4j
public class AuthorizeController {

    @Resource
    private GiteeProvider giteeProvider;

    @Value("${gitee.client.id}")
    private String clientID;
    @Value("${gitee.redirect.uri}")
    private String redirectUri;
    @Value("${gitee.client.secret}")
    private String clientSecret;

    @Resource
    private UserService userService;

    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           HttpServletResponse httpServletResponse) throws IOException {
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(redirectUri);
        accessTokenDTO.setClient_id(clientID);
        accessTokenDTO.setClient_secret(clientSecret);
        String accessToken = giteeProvider.getAccessToken(accessTokenDTO);
        GiteeUser giteeUser = giteeProvider.getUser(accessToken);
        System.out.println(giteeUser.getName());
        if (giteeUser.getId() != null) {
            //登录成功，写session和cookie,以及写到数据库中
            User user = new User();
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setName(giteeUser.getName());
            user.setAccountId(String.valueOf(giteeUser.getId()));
            user.setAvatarUrl(giteeUser.getAvatarUrl());
            userService.createOrUpdate(user);
            httpServletResponse.addCookie(new Cookie("token", token));
//            httpServletRequest.getSession().setAttribute("giteeUser",giteeUser);
        } else {
            log.error("callback get gitee error,{}", giteeUser);
            //登录失败，重新登录

        }
        return "redirect:/";
    }


    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response) {
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }

}
